<template>
    <div class="customer-view">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>我的客户</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="search-area">
            <el-card shadow="never" class="search-card">
                <el-form :inline="true" :model="searchForm" class="search-form">
                    <div class="search-inputs">
                        <el-form-item>
                            <el-input v-model="searchForm.name" placeholder="输入微信昵称" clearable
                                @keyup.enter="fetchCustomerList(true)" @clear="fetchCustomerList(true)"
                                style="width: 180px">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="searchForm.mobile" placeholder="输入联系电话" clearable
                                @keyup.enter="fetchCustomerList(true)" @clear="fetchCustomerList(true)"
                                style="width: 180px">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="searchForm.tagId" placeholder="选择标签" clearable
                                @change="fetchCustomerList(true)" @clear="fetchCustomerList(true)" style="width: 180px">
                                <el-option v-for="tag in tagListForSelect" :key="tag.id" :label="tag.tagName"
                                    :value="tag.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="searchForm.remark" placeholder="输入备注" clearable
                                @keyup.enter="fetchCustomerList(true)" @clear="fetchCustomerList(true)"
                                style="width: 180px">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="search-buttons">
                        <el-form-item>
                            <el-button type="primary" :icon="Search" @click="fetchCustomerList(true)"
                                style="margin-left: 10px;">
                                搜索
                            </el-button>
                            <el-button type="primary" plain @click="handleSyncWechatContacts" :loading="loading"
                                :icon="Refresh">
                                同步企微客户
                            </el-button>
                        </el-form-item>
                    </div>
                </el-form>
                <div class="action-buttons">
                    <el-form-item>
                        <el-button type="primary" :icon="Plus" @click="handleAddCustomer">新建客户</el-button>
                        <el-button type="primary" :icon="Edit" @click="openTagDialog">标签管理</el-button>
                    </el-form-item>
                </div>
            </el-card>
        </div>

        <div class="customer-list">
            <el-card shadow="never" class="list-card">
                <el-table :data="customerList" style="width: 100%" height="calc(100vh - 300px)" v-loading="loading"
                    @selection-change="handleSelectionChange" @row-click="handleTableRowClick" class="customer-table">
                    <el-table-column type="selection" fixed="left" width="40" align="center" />
                    <el-table-column prop="name" label="微信昵称" width="120" align="center" />
                    <el-table-column label="头像" width="80" align="center">
                        <template #default="{ row }">
                            <el-avatar :size="40" :src="row.avatar || ''" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="studentName" label="学生姓名" width="150" align="center" />
                    <el-table-column prop="mobile" label="联系电话" width="150" align="center" />
                    <el-table-column label="标签" width="180" align="center">
                        <template #default="scope">
                            <div class="tag-wrapper">
                                <el-tag v-for="(tag, index) in parseTags(scope.row.tags)" :key="index">
                                    {{ tag.tag_name }}
                                </el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gender" label="性别" width="80" align="center">
                        <template #default="{ row }">
                            <img v-if="row.gender === 1" style="width: 18px; height: 18px;" :src="boyAvatar" alt="男" />
                            <img v-else-if="row.gender === 2" style="width: 18px; height: 18px;" :src="girlAvatar"
                                alt="女" />
                            <span v-else style="color: #999;">--</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="成员备注" min-width="200" />
                    <el-table-column prop="description" label="成员描述" min-width="200" />
                    <el-table-column prop="addtime" label="添加时间" width="180" align="center">
                        <template #default="{ row }">
                            {{ formatAddTime(row.addtime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180" fixed="right" align="center">
                        <template #default="{ row }">
                            <div class="vertical-buttons">
                                <el-button size="small" type="primary" link
                                    @click.native.stop="handleEnterArchive(row)">录入档案</el-button>
                                <el-button size="small" type="info" link
                                    @click.native.stop="handleViewCommunication(row.externalUserid)">沟通记录</el-button>
                                <el-button size="small" type="success" link
                                    @click.native.stop="handleEnrollCourse(row.externalUserid)">办理课程</el-button>
                                <el-button size="small" type="warning" link
                                    @click.native.stop="openPaymentDialog(row.id)">跟进尾款</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="table-footer">
                    <div class="batch-actions" v-if="selectedIds.length > 0">
                        <el-button size="small" @click="handleBatchDelete" type="danger">批量删除</el-button>
                        <span class="selected-count">已选择 {{ selectedIds.length }} 项</span>
                    </div>
                    <el-pagination v-model:current-page="paginationStore.pagination.current"
                        v-model:page-size="paginationStore.pagination.size" :page-sizes="[5, 10, 20, 50]" :small="false"
                        :background="true" layout="prev, pager, next, jumper" :total="paginationStore.pagination.total"
                        @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
                        class="pagination" />
                </div>
            </el-card>
        </div>

        <!-- 新建客户对话框 -->
        <el-dialog title="新建客户" v-model="addDialogVisible" width="600px">
            <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
                <el-form-item label="微信昵称" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入微信昵称" />
                </el-form-item>
                <el-form-item label="联系电话" prop="mobile">
                    <el-input v-model="addForm.mobile" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="addForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                        <el-radio :label="0">未知</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像">
                    <div class="custom-avatar-uploader">
                        <div class="avatar-preview" @click="triggerFileInput">
                            <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar" />
                            <div v-else class="avatar-placeholder">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <span>上传头像</span>
                            </div>
                        </div>
                        <input type="file" ref="fileInput" @change="handleFileChange" accept="image/*"
                            style="display: none" />
                        <div class="avatar-actions" v-if="addForm.avatar">
                            <el-button size="small" @click="triggerFileInput">更换</el-button>
                            <el-button size="small" type="danger" @click="removeAvatar">删除</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="成员备注">
                    <el-input v-model="addForm.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="成员描述">
                    <el-input v-model="addForm.description" type="textarea" placeholder="请输入描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAddForm">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 跟进尾款对话框 -->
        <el-dialog title="跟进尾款" v-model="paymentDialogVisible" width="50%">
            <div class="payment-followup-dialog">
                <el-button :icon="Plus" type="primary" class="add-record-btn" @click="showNewRecordInput = true">
                    新增记录
                </el-button>

                <div class="timeline-container">
                    <div class="timeline-item" v-for="(record, index) in paymentRecords" :key="record.id"
                        @mouseenter="isHoveredRecord = record.id" @mouseleave="isHoveredRecord = null">
                        <div class="timeline-date">{{ formatDate(record.nextFollowTime) }}</div>

                        <div class="timeline-step">
                            <div class="step-dot" :style="{ backgroundColor: getStatusColor(record.followStatus) }">
                            </div>
                            <div class="step-line" v-if="index < paymentRecords.length - 1"></div>
                        </div>

                        <div class="timeline-content">
                            <el-button class="delete-btn" type="danger" :icon="Close" circle size="small"
                                @click.stop="handleDeleteRecord(record.id)" v-show="isHoveredRecord === record.id" />

                            <div class="followup-info">
                                <div><strong>跟进状态：</strong>{{ getFollowStatusText(record.followStatus) }}</div>
                                <div><strong>支付状态：</strong>{{ getPaymentStatusText(record.paymentStatus) }}</div>
                                <div><strong>尾款金额：</strong>¥{{ record.totalDue.toFixed(2) }}</div>
                            </div>
                        </div>
                    </div>

                    <div class="new-record-input" v-if="showNewRecordInput">
                        <el-date-picker v-model="newRecord.nextFollowTime" type="date" placeholder="选择下次跟进时间"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="date-input" />
                        <div class="timeline-step-placeholder">
                            <div class="step-dot"></div>
                        </div>
                        <div class="new-record-fields">
                            <el-input-number v-model="newRecord.paymentAmount" :min="0" :precision="2"
                                placeholder="尾款金额" class="amount-input" />
                        </div>
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closePaymentDialog">取消</el-button>
                    <el-button type="primary" @click="savePaymentRecord">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 沟通记录对话框 -->
        <el-dialog title="沟通记录" v-model="communicationDialogVisible" width="900px">
            <div style="margin-bottom: 16px;">
                <el-button type="primary" :icon="Plus" @click="handleAddCommunication">添加沟通记录</el-button>
            </div>
            <div class="communication-table-container">
                <el-table :data="communicationRecords" style="width: 100%" border>
                    <el-table-column label="图片" min-width="120" align="center">
                        <template #default="{ row }">
                            <div v-if="row.fileList && row.fileList.length > 0" class="image-preview-container">
                                <img v-for="(file, idx) in row.fileList" :key="idx" :src="file.url"
                                    class="image-thumbnail"
                                    @click="previewImage(file.url, row.fileList.map(f => f.url))"
                                    :alt="`沟通记录图片 ${idx + 1}`" />
                            </div>
                            <span v-else class="no-file">无</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="followWay" label="跟进方式" width="120" align="center" />
                    <el-table-column prop="followDate" label="跟进时间" width="180" align="center" />
                    <el-table-column prop="nextFollowDate" label="下次跟进时间" width="180" align="center" />
                    <el-table-column prop="content" label="跟进内容" min-width="300" />
                    <el-table-column label="操作" width="100" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button size="small" type="danger" :icon="Close"
                                @click="handleDeleteCommunication(row.id)" :disabled="loading">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="communicationDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 简化的图片预览弹窗 -->
        <el-dialog v-model="imagePreviewVisible" width="60%" :show-close="true" :close-on-click-modal="true"
            :append-to-body="true">
            <div class="image-preview-wrapper">
                <img :src="currentPreviewImage" class="preview-image">
            </div>
        </el-dialog>

        <!-- 添加沟通记录对话框 -->
        <el-dialog title="添加沟通记录" v-model="addCommunicationDialogVisible" width="600px">
            <el-form :model="newCommunicationRecord" :rules="communicationRules" ref="communicationFormRef"
                label-width="120px">
                <el-form-item label="跟进方式" prop="followWay">
                    <el-select v-model="newCommunicationRecord.followWay" placeholder="请选择跟进方式" clearable>
                        <el-option label="电话" value="电话"></el-option>
                        <el-option label="企业微信" value="企业微信"></el-option>
                        <el-option label="面访" value="面访"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="回访日期" prop="followDate">
                    <el-date-picker v-model="newCommunicationRecord.followDate" type="date" placeholder="选择回访日期"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"></el-date-picker>
                </el-form-item>
                <el-form-item label="下次回访日期" prop="nextFollowDate">
                    <el-date-picker v-model="newCommunicationRecord.nextFollowDate" type="date" placeholder="选择下次回访日期"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"></el-date-picker>
                </el-form-item>

                <el-form-item label="企微提醒" v-if="newCommunicationRecord.nextFollowDate">
                    <el-switch v-model="isReminder" :active-value="1" :inactive-value="0" active-text="提醒"
                        inactive-text="不提醒" />
                </el-form-item>

                <el-form-item label="沟通内容" prop="content">
                    <el-input v-model="newCommunicationRecord.content" type="textarea" placeholder="请输入详细沟通内容" :rows="4"
                        :maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="上传图片">
                    <el-upload :http-request="handleCustomUpload" :file-list="uploadFileList"
                        accept=".jpg,.jpeg,.png,.gif" :on-remove="handleFileRemove" :auto-upload="true"
                        :before-upload="beforeUpload">
                        <el-button type="primary">点击上传图片</el-button>
                        <template #tip>
                            <div class="el-upload__tip">支持jpg/png/gif格式，单个文件不超过5MB</div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addCommunicationDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveCommunicationRecord">确认保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 标签列表弹窗（一级弹窗） -->
        <el-dialog title="标签管理" v-model="tagDialogVisible" width="600px">
            <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
                <el-input v-model="tagSearch" placeholder="搜索标签" clearable size="small" style="width: 200px;"
                    @keyup.enter="fetchTagList" @clear="fetchTagList">
                    <template #prefix>
                        <el-icon class="el-input__icon">
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-button type="primary" :icon="Plus" size="small" @click="showAddTagDialog">
                    新增标签
                </el-button>
            </div>

            <!-- 标签列表 -->
            <div class="tag-list-container" v-loading="tagLoading">
                <div v-if="tagList.length > 0" class="tag-grid">
                    <el-tag v-for="tag in tagList" :key="tag.id" type="primary" closable
                        @close="handleDeleteTag(tag.id)"
                        style="margin: 0 8px 8px 0; padding: 8px 12px; cursor: pointer;">
                        {{ tag.tagName }}
                    </el-tag>
                </div>
                <div v-else class="empty-tip" style="text-align: center; padding: 40px 0; color: #999;">
                    <el-icon size="48" style="margin-bottom: 16px;">
                        <Document />
                    </el-icon>
                    <p>暂无标签数据</p>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="tagDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 新增标签弹窗（二级弹窗） -->
        <el-dialog title="新增标签" v-model="addTagDialogVisible" width="400px">
            <el-form :model="addTagForm" :rules="addTagRules" ref="addTagFormRef" label-width="80px">
                <el-form-item label="标签名称" prop="tagName">
                    <el-input v-model="addTagForm.tagName" placeholder="请输入标签名称" maxlength="20" show-word-limit />
                </el-form-item>
                <el-form-item label="标签描述">
                    <el-input v-model="addTagForm.description" type="textarea" placeholder="请输入标签描述（选填）" :rows="2"
                        maxlength="100" show-word-limit />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addTagDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAddTagForm">确认添加</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 标签修改弹窗 -->
        <el-dialog title="修改客户标签" v-model="editTagDialogVisible" width="500px" destroy-on-close>
            <el-form :model="editTagForm" ref="editTagFormRef" label-width="100px">
                <el-form-item label="客户标签" required>
                    <el-select v-model="editTagForm.selectedTagIds" multiple placeholder="请选择标签" clearable
                        style="width: 100%">
                        <el-option v-for="tag in tagListForSelect" :key="tag.id" :label="tag.tagName"
                            :value="tag.id"></el-option>
                    </el-select>
                    <div class="tag-tip" style="margin-top: 8px; font-size: 12px; color: #666">
                        提示：多选标签可批量为客户添加/移除标签
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editTagDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEditTagForm">确认保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Close, Refresh, Document, Edit } from '@element-plus/icons-vue'
import { getCustomerList, deleteCustomerRelation, addCustomerRelation, synchWeComCustomer } from '../../../api/consultant/user'
import { getFollowUpList, addFollowUp, deleteFollowUp } from '../../../api/consultant/followup'
import { getFollowList, addFollow, uploadImage, deleteFollow } from '../../../api/consultant/follow'
import { getTagList, addTag, deleteTag, addUserTag } from '../../../api/consultant/tag'
import boyAvatar from '../../../assets/boy.svg'
import girlAvatar from '../../../assets/girl.svg'
import { useAuthStore } from '../../../stores/auth'
// 引入Pinia分页状态仓库
import { useCustomerPaginationStore } from '../../../stores/customerPagination'

const authStore = useAuthStore()
const router = useRouter()
// 实例化分页状态仓库
const paginationStore = useCustomerPaginationStore()

// 搜索表单
const searchForm = ref({
    name: '',
    mobile: '',
    remark: '',
    tagId: ''
})

const tagListForSelect = ref([])

// 客户列表相关
const customerList = ref([])
const selectedIds = ref([])
const loading = ref(false)

// 新建客户对话框
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
    name: '',
    mobile: '',
    gender: 0,
    avatar: '',
    remark: '',
    description: '',
    add_way: 1
})
const addRules = reactive({
    name: [
        { required: true, message: '请输入微信昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
    ],
    mobile: [
        { required: false, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ]
})

// 尾款跟进相关
const paymentDialogVisible = ref(false)
const showNewRecordInput = ref(false)
const currentCustomerId = ref(null)
const paymentRecords = ref([])
const newRecord = reactive({
    externalUserid: '',
    courseId: '',
    totalDue: 0,
    followUser: '',
    nextFollowTime: '',
    paymentAmount: 0
})
const isHoveredRecord = ref(null)

// 沟通记录相关
const communicationDialogVisible = ref(false)
const addCommunicationDialogVisible = ref(false)
const communicationRecords = ref([])
const communicationFormRef = ref(null)
const uploadFileList = ref([])
const newCommunicationRecord = reactive({
    followWay: '',
    followDate: '',
    nextFollowDate: '',
    content: ''
})
const communicationRules = reactive({
    followWay: [
        { required: true, message: '请选择跟进方式', trigger: 'change' }
    ],
    followDate: [
        { required: true, message: '请选择回访日期', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入沟通内容', trigger: 'blur' }
    ]
})

// 企微提醒开关状态（0=不提醒，1=提醒，默认0）
const isReminder = ref(0)

// 图片预览相关变量
const imagePreviewVisible = ref(false)
const currentPreviewImage = ref('')
const previewImageList = ref([])

// 文件上传相关
const fileInput = ref(null)

// 标签修改相关
const editTagDialogVisible = ref(false)
const editTagFormRef = ref(null)
const editTagForm = reactive({
    externalUserid: null,
    selectedTagIds: []
})

// 解析标签字符串为数组
const parseTags = (tagsStr) => {
    try {
        if (!tagsStr || typeof tagsStr !== 'string') return [];

        const tags = JSON.parse(tagsStr);
        if (!Array.isArray(tags)) return [];

        return tags.filter(tag => {
            return (
                typeof tag === 'object'
                && tag !== null
                && 'tag_name' in tag
                && tag.tag_name !== null
                && tag.tag_name !== undefined
                && typeof tag.tag_name === 'string'
                && tag.tag_name.trim() !== ''
            );
        });
    } catch (err) {
        console.error("标签解析失败:", err);
        return [];
    }
};

// 标签管理相关
const tagDialogVisible = ref(false)
const addTagDialogVisible = ref(false)
const tagLoading = ref(false)
const tagSearch = ref('')
const tagList = ref([])
const addTagFormRef = ref(null)

// 新增标签表单数据（适配接口字段）
const addTagForm = reactive({
    tagName: '',
    description: ''
})

// 新增标签表单验证规则
const addTagRules = reactive({
    tagName: [
        { required: true, message: '请输入标签名称', trigger: 'blur' },
        { min: 1, max: 20, message: '标签名称长度为1-20个字符', trigger: 'blur' }
    ]
})

// 格式化时间
const formatAddTime = (timeString) => {
    if (!timeString) return '--'
    try {
        const date = new Date(timeString);
        if (isNaN(date.getTime())) return '--';
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        console.error('时间格式化错误:', error);
        return '--';
    }
}

const formatDate = (dateString) => {
    if (!dateString) return '--'
    return dateString.split(' ')[0]
}

// 解析图片URL为图片列表
const parseFileUrls = (fileUrls) => {
    if (!fileUrls) return [];
    const urls = Array.isArray(fileUrls) ? fileUrls : fileUrls.split(',');
    return urls.map(url => {
        const urlParts = url.split('/');
        const fileName = urlParts[urlParts.length - 1];
        return { url, name: fileName };
    }).filter(item => item.url);
}

// 状态文本转换
const getFollowStatusText = (status) => {
    const statusMap = { 0: '待跟进', 1: '跟进中', 2: '已完成', 3: '已失效' };
    return statusMap[status] || '未知状态'
}

const getPaymentStatusText = (status) => {
    const statusMap = { 0: '未支付', 1: '已支付', 2: '部分支付' };
    return statusMap[status] || '未知支付状态'
}

const getStatusColor = (status) => {
    const colorMap = { 0: '#909399', 1: '#e6a23c', 2: '#409eff', 3: '#67c23a' };
    return colorMap[status] || '#909399'
}

// 图片预览方法
const previewImage = (url, list) => {
    currentPreviewImage.value = url
    previewImageList.value = list
    imagePreviewVisible.value = true
}

// 获取客户列表
const fetchCustomerList = async (isSearch = false) => {
    // 搜索时重置到第一页
    if (isSearch) {
        paginationStore.updateCurrentPage(1)
    }

    loading.value = true
    try {
        const params = {
            ...searchForm.value,
            pageNum: paginationStore.pagination.current,
            pageSize: paginationStore.pagination.size
        }
        const res = await getCustomerList(params)
        customerList.value = res.rows || []
        paginationStore.updateTotal(res.total || 0)
    } catch (error) {
        console.error('获取客户列表失败:', error)
        ElMessage.error('获取客户列表失败')
    } finally {
        loading.value = false
    }
}

// 处理每页条数变化
const handlePageSizeChange = (newSize) => {
    paginationStore.updatePageSize(newSize)
    paginationStore.updateCurrentPage(1) // 切换每页条数时重置到第一页
    fetchCustomerList()
}

// 处理页码变化
const handleCurrentPageChange = (newPage) => {
    paginationStore.updateCurrentPage(newPage)
    fetchCustomerList()
}

// 获取跟进记录
const fetchFollowUpRecords = async (customerId) => {
    try {
        const res = await getFollowUpList({ externalUserid: customerId })
        paymentRecords.value = res.rows || []
        if (paymentRecords.value.length > 0) {
            const lastRecord = paymentRecords.value[paymentRecords.value.length - 1]
            newRecord.totalDue = lastRecord.totalDue
            newRecord.paymentAmount = 0
        }
    } catch (error) {
        ElMessage.error('加载记录失败')
    }
}

// 删除跟进记录
const handleDeleteRecord = async (id) => {
    try {
        await ElMessageBox.confirm('确定要删除这条跟进记录吗？删除后不可恢复', '警告', {
            confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning', confirmButtonClass: 'el-button--danger'
        })
        await deleteFollowUp([id])
        ElMessage.success('删除成功')
        await fetchFollowUpRecords(currentCustomerId.value)
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除跟进记录失败:', error)
            ElMessage.error('删除失败: ' + (error.message || '服务器错误'))
        }
    }
}

// 同步企微客户
const handleSyncWechatContacts = async () => {
    try {
        await ElMessageBox.confirm('确定要从企业微信同步客户数据吗？', '同步确认', {
            confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
        })
        loading.value = true
        ElMessage.info('正在同步企业微信客户数据，请稍候...')
        const { code, msg } = await synchWeComCustomer({ createBy: authStore.userId })
        if (code === 200) {
            ElMessage.success({ message: msg || '同步完成！', duration: 6000 })
            await fetchCustomerList()
        } else {
            ElMessage.error(msg || '同步失败，请稍后重试')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('同步企业微信客户失败:', error)
            ElMessage.error(`同步失败: ${error.message || '服务器错误'}`)
        }
    } finally {
        loading.value = false
    }
}

// 录入档案
const handleEnterArchive = async (row) => {
    try {
        await router.push(`/consulting/ai-trainer-registration?data=${encodeURIComponent(JSON.stringify(row))}`)
    } catch (err) {
        console.error('路由跳转失败:', err)
        ElMessage.error('页面跳转失败，请稍后重试')
    }
}

// 查看沟通记录
const handleViewCommunication = async (id) => {
    communicationDialogVisible.value = true;
    currentCustomerId.value = id;
    await fetchCommunicationRecords(id)
};

// 添加沟通记录
const handleAddCommunication = () => {
    const today = new Date().toISOString().split('T')[0];
    Object.assign(newCommunicationRecord, {
        followWay: '企业微信',
        followDate: today,
        nextFollowDate: '',
        content: '',
        followFile: ''
    });
    isReminder.value = 0;
    uploadFileList.value = [];
    if (communicationFormRef.value) communicationFormRef.value.resetFields();
    addCommunicationDialogVisible.value = true;
};

// 保存沟通记录
const saveCommunicationRecord = async () => {
    try {
        await communicationFormRef.value.validate();
    } catch (error) {
        ElMessage.warning('请完善必填的沟通记录信息');
        return;
    }

    const requestParams = {
        externalUserid: currentCustomerId.value,
        followType: newCommunicationRecord.followWay,
        followTime: newCommunicationRecord.followDate,
        followNextTime: newCommunicationRecord.nextFollowDate,
        followContent: newCommunicationRecord.content,
        followFile: uploadFileList.value.length > 0
            ? uploadFileList.value.map(file => file.fileUrl || '').filter(Boolean).join(',')
            : '',
        isReminder: isReminder.value
    };

    try {
        loading.value = true;
        await addFollow(requestParams);
        ElMessage.success('沟通记录添加成功');
        await fetchCommunicationRecords(currentCustomerId.value);
        addCommunicationDialogVisible.value = false;
        uploadFileList.value = [];
    } catch (error) {
        console.error('保存沟通记录失败:', error);
        if (error.message.includes('404')) ElMessage.error('接口不存在，请检查请求地址');
        else if (error.message.includes('500')) ElMessage.error('服务器错误，请稍后重试');
        else ElMessage.error('保存失败：' + (error.message || '未知错误'));
    } finally {
        loading.value = false;
    }
};

// 根据客户ID获取沟通记录列表
const fetchCommunicationRecords = async (externalUserid) => {
    if (!externalUserid) return;
    try {
        loading.value = true;
        const res = await getFollowList({ externalUserid });
        communicationRecords.value = res.rows?.map(record => ({
            id: record.id,
            followWay: record.followType,
            followDate: record.followTime,
            nextFollowDate: record.followNextTime,
            content: record.followContent,
            fileUrl: record.followFile,
            fileList: parseFileUrls(record.followFile)
        })) || [];
    } catch (error) {
        console.error('获取沟通记录失败:', error);
        ElMessage.error('加载沟通记录失败，请刷新重试');
    } finally {
        loading.value = false;
    }
};

// 删除沟通记录
const handleDeleteCommunication = async (recordId) => {
    if (!recordId) {
        ElMessage.warning('记录ID不存在，无法删除');
        return;
    }
    try {
        await ElMessageBox.confirm(
            '确定要删除这条沟通记录吗？删除后不可恢复',
            '删除确认',
            { confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning', confirmButtonClass: 'el-button--danger' }
        );
        loading.value = true;
        await deleteFollow([recordId]);
        ElMessage.success('沟通记录删除成功');
        await fetchCommunicationRecords(currentCustomerId.value);
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除沟通记录失败:', error);
            ElMessage.error('删除失败：' + (error.message || '服务器错误'));
        }
    } finally {
        loading.value = false;
    }
};

// 上传前校验（仅允许图片）
const beforeUpload = (file) => {
    if (uploadFileList.value.length >= 1) {
        ElMessage.warning('最多只能上传1张图片');
        return false;
    }

    // 仅允许图片格式
    const acceptTypes = ['image/jpeg', 'image/png', 'image/gif'];
    const isImage = acceptTypes.includes(file.type);
    if (!isImage) {
        ElMessage.error('仅支持jpg/png/gif格式的图片！');
        return false;
    }

    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB!');
        return false;
    }

    return true;
};

// 自定义图片上传逻辑
const handleCustomUpload = async (options) => {
    const file = options.file;
    if (!file) return;

    options.onProgress({ percent: 0 }, file);

    try {
        loading.value = true;
        const formData = new FormData();
        formData.append('file', file);

        const res = await uploadImage(formData);
        console.log('图片上传接口返回结果：', res);

        // 构造图片对象，包含URL信息
        const uploadFile = {
            uid: res.uid || file.uid,
            name: file.name,
            raw: file,
            size: file.size,
            status: 'success',
            fileUrl: res.name
        };

        uploadFileList.value = [uploadFile];
        console.log('上传成功后的图片列表：', uploadFileList.value);

        options.onSuccess(uploadFile, file);
        ElMessage.success(`${file.name} 上传成功`);
    } catch (error) {
        options.onError(error, file);
        ElMessage.error(`${file.name} 上传失败，请重试`);
    } finally {
        loading.value = false;
        options.onProgress({ percent: 100 }, file);
    }
};

// 移除已上传的图片
const handleFileRemove = (uploadFile, uploadFiles) => {
    uploadFileList.value = uploadFiles;
    console.log('图片移除后列表：', uploadFileList.value);
};

// 办理课程
const handleEnrollCourse = (id) => {
    try {
        router.push({ path: '/consulting/detail', query: { id, openDialog: 'course' } })
    } catch (err) {
        console.error('路由跳转失败:', err)
        ElMessage.error('页面跳转失败，请稍后重试')
    }
}

// 打开尾款跟进对话框
const openPaymentDialog = async (customerId) => {
    currentCustomerId.value = customerId
    paymentDialogVisible.value = true
    showNewRecordInput.value = false
    const today = new Date().toISOString().split('T')[0];
    Object.assign(newRecord, {
        externalUserid: customerId,
        courseId: '',
        totalDue: 0,
        paymentAmount: 0,
        followUser: authStore.userId,
        nextFollowTime: today,
        followStatus: 0,
        followRemarks: ''
    })
    await fetchFollowUpRecords(customerId)
}

// 保存尾款记录
const savePaymentRecord = async () => {
    if (showNewRecordInput.value) {
        try {
            const recordData = {
                externalUserid: currentCustomerId.value,
                courseId: newRecord.courseId,
                totalDue: newRecord.paymentAmount,
                followUser: authStore.userId,
                nextFollowTime: newRecord.nextFollowTime
            }
            await addFollowUp(recordData)
            ElMessage.success('尾款跟进记录已保存')
            await fetchFollowUpRecords(currentCustomerId.value)
            showNewRecordInput.value = false
            paymentDialogVisible.value = false
            newRecord.paymentAmount = 0
            newRecord.nextFollowTime = ''
        } catch (error) {
            ElMessage.error('保存失败: ' + error.message)
        }
    }
}

// 关闭尾款对话框
const closePaymentDialog = () => {
    paymentDialogVisible.value = false
    showNewRecordInput.value = false
    Object.assign(newRecord, {
        nextFollowTime: '',
        followStatus: 0,
        paymentAmount: 0,
        followRemarks: ''
    })
}

// 新建客户
const handleAddCustomer = () => {
    addDialogVisible.value = true
    Object.assign(addForm, {
        name: '',
        mobile: '',
        gender: 0,
        avatar: '',
        remark: '',
        description: ''
    })
}

// 触发文件上传（头像）
const triggerFileInput = () => {
    fileInput.value.click()
}

// 处理头像上传
const handleFileChange = async (e) => {
    const file = e.target.files[0]
    if (!file) return
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return
    }
    try {
        loading.value = true
        const formData = new FormData()
        formData.append('file', file)
        const res = await uploadImage(formData)
        addForm.avatar = res.name
        ElMessage.success('头像上传成功')
    } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('头像上传失败')
    } finally {
        loading.value = false
        e.target.value = ''
    }
}

// 移除头像
const removeAvatar = () => {
    addForm.avatar = ''
}

// 提交新增客户
const submitAddForm = async () => {
    try {
        await addFormRef.value.validate()
        const params = {
            name: addForm.name,
            mobile: addForm.mobile,
            gender: addForm.gender,
            avatar: addForm.avatar || undefined,
            remark: addForm.remark || undefined,
            description: addForm.description || undefined,
            add_way: addForm.add_way,
            userid: authStore.userId,
            createTime: Math.floor(Date.now() / 1000)
        }
        loading.value = true
        await addCustomerRelation(params)
        ElMessage.success('客户添加成功')
        addDialogVisible.value = false
        fetchCustomerList()
    } catch (error) {
        if (error.name !== 'ValidationError') {
            console.error('添加客户失败:', error)
            ElMessage.error('添加客户失败: ' + (error.message || '服务器错误'))
        }
    } finally {
        loading.value = false
    }
}

// 删除客户
const handleDeleteCustomers = async (ids) => {
    try {
        await ElMessageBox.confirm('确定要删除选中的客户吗?', '提示', {
            confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
        })
        await deleteCustomerRelation(ids)
        ElMessage.success('删除成功')
        fetchCustomerList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id)
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请至少选择一项')
        return
    }
    handleDeleteCustomers(selectedIds.value)
}

// 获取标签列表
const fetchTagList = async () => {
    tagLoading.value = true
    try {
        const params = { tagName: tagSearch.value }
        const res = await getTagList(params)
        tagList.value = res.rows || []
        tagListForSelect.value = res.rows || []
    } catch (error) {
        console.error('获取标签列表失败:', error)
        ElMessage.error('获取标签列表失败，请重试')
    } finally {
        tagLoading.value = false
    }
}

// 打开标签列表弹窗
const openTagDialog = () => {
    tagDialogVisible.value = true

    nextTick(() => {
        fetchTagList()
    })
}

// 打开新增标签弹窗
const showAddTagDialog = () => {
    addTagForm.tagName = ''
    addTagForm.description = ''
    if (addTagFormRef.value) {
        addTagFormRef.value.resetFields()
    }
    addTagDialogVisible.value = true
}

// 提交新增标签
const submitAddTagForm = async () => {
    try {
        await addTagFormRef.value.validate()
        await addTag({
            tagName: addTagForm.tagName,
            description: addTagForm.description
        })
        ElMessage.success('标签新增成功')
        addTagDialogVisible.value = false
        fetchTagList()
    } catch (error) {
        if (error.name !== 'ValidationError') {
            console.error('新增标签失败:', error)
            ElMessage.error('新增标签失败: ' + (error.message || '服务器错误'))
        }
    }
}

// 删除标签
const handleDeleteTag = async (tagId) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该标签吗？删除后相关关联数据可能受影响',
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                confirmButtonClass: 'el-button--danger'
            }
        )
        await deleteTag(tagId)
        ElMessage.success('标签删除成功')

        fetchTagList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除标签失败:', error)
            ElMessage.error('删除标签失败，请重试')
        }
    }
}

// 表格行点击事件：打开标签修改弹窗
const handleTableRowClick = (row) => {
    editTagForm.externalUserid = row.externalUserid;

    const currentTags = parseTags(row.tags);
    editTagForm.selectedTagIds = currentTags.map(tag => tag.id) || [];

    editTagDialogVisible.value = true;
};

// 提交新增后的客户标签
const submitEditTagForm = async () => {
    if (!editTagForm.externalUserid) {
        ElMessage.warning('客户信息异常，请重新选择客户');
        return;
    }

    try {
        const params = {
            externalUserid: editTagForm.externalUserid,
            tagIds: editTagForm.selectedTagIds
        };
        await addUserTag(params);

        ElMessage.success('客户标签新增成功');
        editTagDialogVisible.value = false;
        fetchCustomerList();
    } catch (error) {
        console.error('新增客户标签失败:', error);
        ElMessage.error('标签新增失败：' + (error.message || '服务器错误'));
    }
};

// 页面加载时获取客户列表并且初始化标签选择器数据
onMounted(() => {
    fetchCustomerList()
    fetchTagList()
})
</script>

<style scoped>
.customer-view {
    width: 100%;
    overflow-x: auto;
    box-sizing: border-box;
}

.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.search-area {
    margin-bottom: 20px;
}

:deep(.el-card__body) {
    padding: 0 !important;
}

:deep(.el-input__wrapper) {
    width: 200px;
    box-sizing: border-box;
}

.search-card,
.list-card {
    border: none;
}

.search-form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin-bottom: 10px;
}

.action-buttons {
    width: 100%;
    display: flex;
    justify-content: flex-end;
}

.search-inputs {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: space-around;
}

.search-area .el-form-item {
    margin-bottom: 0;
    margin-right: 0
}

.search-inputs .el-form-item:last-child {
    margin-right: 0;
}

.customer-table {
    cursor: pointer;
    --el-table-border-color: transparent;
    --el-table-border: none;
}

.customer-table :deep(.el-table__header-wrapper) .el-table__cell {
    background-color: #f5f7fa;
}

.customer-table :deep(.el-table__row) .el-table__cell {
    border-bottom: 1px solid #f0f0f0;
}

.customer-table :deep(.el-table__row):hover .el-table__cell {
    background-color: #f5f7fa;
}

.tag-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    width: 100%;
}

:deep(.el-tag) {
    max-width: 80px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
}

.batch-actions .selected-count {
    margin-left: 10px;
    color: #666;
    font-size: 14px;
}

.pagination {
    margin-left: auto;
}

.vertical-buttons {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
}

.vertical-buttons .el-button {
    margin: 0;
    padding: 13px;
}

.payment-followup-dialog {
    padding: 10px;
}

.add-record-btn {
    margin-bottom: 20px;
}

.timeline-container {
    display: flex;
    flex-direction: column;
    max-height: 440px;
    overflow-y: auto;
    padding-right: 8px;
}

.timeline-container::-webkit-scrollbar {
    width: 8px;
    background-color: #f5f5f5;
    border-radius: 4px;
}

.timeline-container::-webkit-scrollbar-thumb {
    background-color: #c1c1c1;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.timeline-container::-webkit-scrollbar-thumb:hover {
    background-color: #a8a8a8;
}

.timeline-item {
    display: flex;
    align-items: flex-start;
}

.timeline-date {
    width: 200px;
    color: #606266;
    font-size: 13px;
    text-align: right;
    padding-right: 20px;
}

.timeline-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0 15px;
    position: relative;
    width: 20px;
    height: 90px;
}

.step-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #409eff;
    flex-shrink: 0;
}

.step-line {
    width: 3px;
    height: 100%;
    background-color: #e4e7ed;
}

.timeline-content {
    position: relative;
    flex: 1;
    color: #303133;
    padding-left: 15px;
    padding: 10px;
    border-radius: 4px;
    transition: all 0.3s ease;
}

.delete-btn {
    position: absolute;
    top: 0;
    right: 0;
    opacity: 0;
    z-index: 1;
}

.timeline-item:hover .delete-btn {
    opacity: 1;
}

.followup-info div {
    margin-bottom: 5px;
    font-size: 14px;
}

.followup-info div:last-child {
    margin-bottom: 0;
}

.new-record-input {
    display: flex;
    align-items: flex-start;
    margin-top: 30px;
}

.timeline-step-placeholder {
    width: 20px;
    margin: 0 15px;
    display: flex;
    justify-content: center;
}

.date-input {
    width: 160px;
}

.new-record-fields {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.status-select,
.amount-input {
    width: 100%;
}

.remarks-input {
    width: 100%;
}

/* 沟通记录表格容器 - 固定高度 */
.communication-table-container {
    height: 400px;
    overflow-y: auto;
    border-radius: 4px;
}

/* 优化滚动条样式 */
.communication-table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.communication-table-container::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 4px;
}

.communication-table-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.communication-table-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
}

/* 自定义头像上传样式 */
.custom-avatar-uploader {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
}

.avatar-preview {
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    transition: border-color 0.3s;
}

.avatar-preview:hover {
    border-color: var(--el-color-primary);
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8c939d;
}

.avatar-placeholder .el-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.avatar-actions {
    display: flex;
    gap: 8px;
}

/* 图片附件样式 */
.image-preview-container {
    display: flex;
    gap: 8px;
    justify-content: center;
    padding: 4px 0;
    flex-wrap: wrap;
}

/* 图片缩略图样式 */
.image-thumbnail {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    cursor: zoom-in;
    border: 1px solid #eee;
    object-fit: cover;
    transition: all 0.2s ease;
}

.image-thumbnail:hover {
    border-color: var(--el-color-primary);
    transform: scale(1.05);
}

/* 无图片时的样式 */
.no-file {
    color: #909399;
    font-size: 14px;
}

/* 图片预览弹窗样式 */
.image-preview-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}

.preview-image {
    max-width: 100%;
    max-height: 80vh;
    object-fit: contain;
}

/* 上传组件提示文字样式 */
:deep(.el-upload__tip) {
    margin-top: 5px;
    font-size: 12px;
}

/* 标签相关样式 */
.tag-list-container {
    max-height: 400px;
    overflow-y: auto;
}

.tag-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

/* 标签关闭按钮样式优化 */
:deep(.el-tag__close) {
    margin-left: 8px;
}

:deep(.el-tag__close:hover) {
    background-color: rgba(0, 0, 0, 0.1);
}
</style>
